//
// Created by 文道江 on 15/11/25.
// Copyright (c) 2015 WenDaojiang. All rights reserved.
//

#import "SplashScreenView.h"
#import "UIImageView+AFNetworking.h"
#import "FZEasyFile.h"


@implementation SplashScreenView {
    NSInteger _showTime ;
    UIImageView *_imageView;
    UIView *_timeView;
    UILabel *_timeLabel;
    NSTimer *_timer;
    id _image;
}

+ (instancetype)viewWithFrame:(CGRect)frame Image:(id)image showTime:(NSInteger)time{
    SplashScreenView *instance = [self instance];
    instance.frame = frame;
    [instance setShowTime:time image:image];
    return instance;
}

+ (instancetype)instance {
    static SplashScreenView *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }

    return _instance;
}

- (void)setShowTime:(NSInteger)showTime image:(id)image {
    _showTime = showTime;
    _image = image;
}


- (void)showWithImage:(id)image Time:(NSInteger) time{
    [self initViewWithTime:time Image:image];
}

- (void) initViewWithTime:(NSInteger) time Image:(id)image{
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.backgroundColor = [UIColor blackColor];

    /* 图片 view start */
    _imageView = [[UIImageView alloc] initWithFrame: self.frame];
    _imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    if (image){
        _image = image;
    }
    if ([_image isKindOfClass:[UIImage class]]){
        _imageView.image = _image;
    } else if([_image isKindOfClass:[NSString class]]){
        NSString *imgUrl = _image;
        if ([imgUrl hasPrefix:@"http"]){
            //@"http://files.colabug.com/forum/201404/10/211934xb0g970llj02dll2.jpg"
            [_imageView setImageWithURL:[NSURL URLWithString: imgUrl]];
        }else{
            if ([FZEasyFile isFileExists:imgUrl]){
                _imageView.image = [UIImage imageWithContentsOfFile:[FZEasyFile fullFileName:imgUrl]];
            }else{
                if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDidLoadError:)])
                    [_delegate imageDidLoadError:[NSError errorWithDomain:@"图片加载错误!请指定可用的图片源." code:0 userInfo:nil]];
                return;
            }
        }
    }else{
        if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDidLoadError:)])
            [_delegate imageDidLoadError:[NSError errorWithDomain:@"图片错误" code:0 userInfo:nil]];
        return;
    }

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick:)];
    _imageView.userInteractionEnabled = YES;
    [_imageView addGestureRecognizer:tapGestureRecognizer];

    [self addSubview: _imageView];
    /* 图片 view end */

    /* 计时/跳过 view start */
    if (_showControl){
        _timeView = [[UIView alloc] initWithFrame:CGRectMake(self.frame.size.width - 50, 30, 40, 40)];
        _timeView.backgroundColor = [UIColor blackColor];
        _timeView.layer.cornerRadius = 20.0F;
        _timeView.layer.opacity = .5F;
        _timeView.userInteractionEnabled = YES;
        UITapGestureRecognizer *skipTap  = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(skipClick:)];
        [_timeView addGestureRecognizer:skipTap];

        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.text = @"跳过";
        _timeLabel.font = [UIFont systemFontOfSize:14.0F];
        _timeLabel.textColor = [UIColor whiteColor];

        [_timeView addSubview: _timeLabel];
        [self addSubview:_timeView];
    }
    /* 计时/跳过 view end */

    if (time){
        _showTime = time;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(start:) userInfo:nil repeats:YES];
    [_timer fireDate];
}

- (void)start:(NSTimer*)theTimer{
    if (_showTime == 0){
        [self hide: YES];
    }else if (_showControl && _showCountdown){
        _timeLabel.text = [NSString stringWithFormat:@"%is", _showTime];
    }
    _showTime--;
}

- (void)hide:(BOOL)animated{
    if (_timer != nil)[_timer setFireDate:[NSDate distantFuture]];
    if (_timeView != nil)[_timeView removeFromSuperview];

    if (animated){
        if ([self.layer animationForKey:@"opacity"] == nil){
            CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
            opacityAnimation.fromValue = @1.0F;
            opacityAnimation.toValue = @0.0F;
            opacityAnimation.duration = 0.6;
            opacityAnimation.repeatCount = 1;
            [self.layer addAnimation:opacityAnimation forKey:@"opacity"];
            [NSTimer scheduledTimerWithTimeInterval:0.5555 target:self selector:@selector(remove) userInfo:nil repeats:NO];
        }else{
            [self.layer removeAllAnimations];
        }
    }else{
        [self remove];
    }
}

- (void) remove{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(viewHidden)]){
        [_delegate viewHidden];
    }
    [self removeFromSuperview];
}

- (void)imageClick:(id)sender {
    [self hide:NO];
    if (_delegate != nil && [_delegate respondsToSelector:@selector(imageClick:)]){
        [_delegate imageClick:_imageView];
    }
}

- (void)skipClick:(id)sender {
    if (_delegate != nil && [_delegate respondsToSelector:@selector(skipClick:)]){
        [_delegate skipClick:_timeLabel];
    }
    [self hide: YES];
}

@end